package com.itcast.clientx.util;

import com.itcast.clientx.bean.Maven;
import com.itcast.clientx.bean.Repository;
import com.itcast.clientx.service.RepositoryService;
import com.itcast.clientx.util.Client;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static javax.management.Query.attr;

@Component
public class Crawler {

    @Autowired
    private Client client;
    @Autowired
    private RepositoryService service;

    /**
     * MVN_SESSION=eyJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7InVpZCI6ImEzN2JkMzMyLWJjZjYtMTFlYi1iZTgwLTc5ZTI2ZDdmNmJiZSJ9LCJleHAiOjE2NTM0NDEzNTIsIm5iZiI6MTYyMTkwNTM1MiwiaWF0IjoxNjIxOTA1MzUyfQ.8l-xVRBwrL4sbSUvEhMxjb5gpJXSfLhEj5SwUFuY0Tk; Max-Age=31536000; Expires=Wed, 25 May 2022 01:15:52 GMT; SameSite=Lax; Path=/; HTTPOnly
     * MVN_SESSION=eyJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7InVpZCI6ImEzN2JkMzMyLWJjZjYtMTFlYi1iZTgwLTc5ZTI2ZDdmNmJiZSJ9LCJleHAiOjE2NTM0NDEzMDUsIm5iZiI6MTYyMTkwNTMwNSwiaWF0IjoxNjIxOTA1MzA1fQ.waQpdfqDQof7r0MupqUyde0FCd-3BlaQ79jw-j6gw8M
     * MVN_SESSION=eyJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7InVpZCI6Ijk2OTIwZTEwLWJkMzYtMTFlYi1hNjIwLTQ5MDY1ZTNjNGRkMSJ9LCJleHAiOjE2NTM0Njg4MjIsIm5iZiI6MTYyMTkzMjgyMiwiaWF0IjoxNjIxOTMyODIyfQ.RMjGl60Ih-bvpdohwDAHhSNRSumC3A85DxUWOIQ_utQ
     * @param content
     */
    public void test(String content){
        String cookie = "MVN_SESSION=eyJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7InVpZCI6ImJiODEyNDUwLWJjZmUtMTFlYi04YzNlLTdiYWEyM2NlNjU3MSJ9LCJleHAiOjE2NTM0Njg2MjIsIm5iZiI6MTYyMTkzMjYyMiwiaWF0IjoxNjIxOTMyNjIyfQ.C3NvOr9uny_-uOp9kc9_VNDKWXJYLq7-VN69AnrkT30";

        for (int i = 1; i <= 10; i++) {
            String html = client.getHTML("https://mvnrepository.com/search?q="+content+"&p="+i,cookie);
            if(html != null){
                this.parseHTML(html,cookie);
            }
            if(html.equals("404")){
                System.out.println("爬取完成");
                return;
            }
        }
        System.out.println("爬取完成");
    }
    public void parseHTML(String html,String cookie){
        Document document = Jsoup.parse(html);
        /**
         * groupId artifactId所在的p标签
         */
        Elements subtitle = document.select(".im .im-header .im-subtitle");
        for (Element p : subtitle) {
            /**
             * groupId
             * artifactId
             * 的a标签
             */
            Elements a = p.select("a");
            System.out.println(255);
            Element a0 = a.get(0);
            String groupid = a0.text().trim();

            Element a1 = a.get(1);
            String artifactid = a1.text().trim();
            String artifactid_href = a1.attr("href");
            artifactid_href = "https://mvnrepository.com"+artifactid_href;
            this.sleep(3*1000);
            /**
             * 包含版本号 发布日期等具体信息页面的数据
             */
            String artifact =client.getHTML(artifactid_href,cookie);
            this.parseartifact(artifact,cookie,groupid,artifactid);
        }
    }
    public void sleep(Integer time){
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    /**
     * 解析artifact详情
     * @param html
     * @param cookie
     */
    public void parseartifact(String html,String cookie,String groupid,String artifactid){
        Repository repository = new Repository();
        repository.setGroupid(groupid);
        repository.setArtifactid(artifactid);

        Document document = Jsoup.parse(html);

        Elements move = document.select("#page > #maincontent > div > .grid");
        /**
         * 说明有项目迁移
         */
        if(move!=null && move.size() > 0){
            Elements ma = move.select("tbody tr td a");
            repository.setMessage(ma.get(0).text().trim());
            repository.setPostu(ma.get(1).text().trim());
        }
        System.out.println(repository);

        int i = -1;
        int j = -1;
        int m = -1;
        int n = -1;
        Elements ths = document.select("#page > #maincontent > div > #snippets > .tab_container > .tab_content > .gridcontainer > .grid > thead > tr > th");
        /**
         * 根据表头决定对应数据在第几列
         */
        int thsize = ths.size();
        if(thsize == 4){
            i = 0;
            j = 1;
            m = 2;
            n = 3;
        }


        /**
         * 想要的版本号等具体信息的tr
         */
        Elements trs = document.select("#page > #maincontent > div > #snippets > .tab_container > .tab_content > .gridcontainer > .grid > tbody > tr");

        List<Maven> list = new ArrayList<>();
        Maven mvn = null;
        int k = 0;
        for (Element tr : trs) {


            System.out.println(k++);
            mvn = new Maven();
            /**
             * groupId
             * artifactId的a标签
             */
            Elements tds = tr.select("td");


            int tdsize = trs.size();

            if(thsize > 4 && thsize == tdsize){

                for (int x = 0; x < thsize; x++) {
                    if(ths.get(x).text().trim().equals("Version")){
                        i = x;
                    }
                    if(ths.get(x).text().trim().equals("Repository")){
                        j = x;
                    }
                    if(ths.get(x).text().trim().equals("Usages")){
                        m = x;
                    }
                    if(ths.get(x).text().trim().equals("Date")){
                        n = x;
                    }
                }
            }
            if(thsize > 4 && thsize == tdsize+1){

                for (int x = 0; x < thsize; x++) {
                    if(ths.get(x).text().trim().equals("Version")){
                        i = x-1;
                    }
                    if(ths.get(x).text().trim().equals("Repository")){
                        j = x-1;
                    }
                    if(ths.get(x).text().trim().equals("Usages")){
                        m = x-1;
                    }
                    if(ths.get(x).text().trim().equals("Date")){
                        n = x-1;
                    }
                }
            }
            /**
             * size
             * 4             Version	Repository	Usages	Date
             * 5 MainVersion Version	Repository	Usages	Date
             * 如果找到的td为5个 表示第一个td显示的是主要版本号
             */
            String version = tds.get(i).select("a").text().trim();
            mvn.setVersion(version);
            /**
             * 仓库
             */
            String store = tds.get(j).select("a").text().trim();
            mvn.setRepository(store);
            String usages = tds.get(m).text().trim().replace(",","").replace(" ","");
            mvn.setUsages(Integer.parseInt(usages));
            String date = tds.get(n).text().trim().replace(" ","");
            String year = date.split(",")[1];
            int month = this.getMathMonth(date.split(",")[0]);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date t = null;
            try {
                t = sdf.parse(year+"-"+month+"-1");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            mvn.setPublishtime(t);
            mvn.setSpringboot(0);
            System.out.println(mvn);
            list.add(mvn);
        }

        /*service.insert(repository,list);*/
    }

    /**
     * 根据文本月份值返回数字月份值
     * @param m 文本月份值
     * @return
     */
    public Integer getMathMonth(String m){
        switch (m){
            case "Jan":
                return 1;

            case "Feb":
                return 2;

            case "Mar":
                return 3;

            case "Apr":
                return 4;

            case "May":
                return 5;

            case "Jun":
                return 6;

            case "Jul":
                return 7;

            case "Aug":
                return 8;

            case "Sep":
                return 9;

            case "Oct":
                return 10;

            case "Nov":
                return 11;

            case "Dec":
                return 12;

            default:
                return null;
        }
    }


    /*public void context() {
        this.
    }*/
}
